package online.westonline.com.westonline.adapter.im;

import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.content.PromptContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.nekocode.badge.BadgeDrawable;
import de.hdodenhof.circleimageview.CircleImageView;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.utils.TimeFormat;
import online.westonline.com.westonline.utils.UiUtlis;

/**
 * 消息展示页面的适配器
 * Created by xiatao on 2018/8/8.
 */

public class HomeMessageAdpter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    //正常类型的
    private int NORMAL_MESSAGE = 0;
    //其他消息类型的
    private int OTHER_MESSAGE = 1;
    private List<Conversation> conversationList = new ArrayList<>();
    private onClicktoChat clicktoChat;

    public void setClicktoChat(onClicktoChat clicktoChat) {
        this.clicktoChat = clicktoChat;
    }

    public void setConversationList(List<Conversation> conversationList) {
        this.conversationList = conversationList;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_message_item, parent, false);
        return new MyNormalmessageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyNormalmessageViewHolder) {
            final MyNormalmessageViewHolder normalmessageViewHolder = (MyNormalmessageViewHolder) holder;
            final Conversation conversation = conversationList.get(position);
            String contentstr = null;
            //暂时不区分type
            int unreadount = conversation.getUnReadMsgCnt();
            //获取最近一条消息
            Message message = conversation.getLatestMessage();
            if (message!=null)
            {
                //加载头像
                if (message.getTargetInfo()!=null)
                {
                    final UserInfo target_userinfo = (UserInfo) message.getTargetInfo();
                    //获取头像(服务器原图)
                    target_userinfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                        @Override
                        public void gotResult(int i, String s, Bitmap bitmap) {
                            if (i==0)
                            {
                                //成功
                                normalmessageViewHolder.imgUserAvator.setImageBitmap(bitmap);
                            }
                            else
                            {
                                Log.e("用户"+target_userinfo.getNickname()+"头像获取失败","原因:"+s);
                            }
                        }
                    });
                }

                if (message != null) {
                    //判断消息类型
                    switch (message.getContentType()) {
                        case text:
                            TextContent textContent = (TextContent) message.getContent();
                            contentstr = textContent.getText();
                            break;
                        case image:
                            contentstr = "[图片]";
                            break;
                        case file:
                            String extra = message.getContent().getStringExtra("video");
                            if (!TextUtils.isEmpty(extra)) {
                                contentstr = "[视频]";
                            } else {
                                contentstr = "[文件]";
                            }
                            break;
                        case video:
                            contentstr = "[视频]";
                            break;
                        case voice:
                            contentstr = "[语音]";
                            break;
                        case custom:
                            //自定义消息,前提示自定义过
                            contentstr = "[]";
                            break;
                        case location:
                            contentstr = "[位置]";
                            break;
                        case prompt:
                            PromptContent promptContent = (PromptContent) message.getContent();
                            contentstr = promptContent.getPromptText();
                            break;
                        case unknown:

                            break;
                        default:

                            break;
                    }


                    //判断该消息是否已读
                    if (!message.haveRead()) {
                        //未读提示
                        //文字提示
                        if (!message.haveRead() && !message.getFromUser().getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                            contentstr = "[未读]" + contentstr;
                            SpannableStringBuilder builder = new SpannableStringBuilder(contentstr);
                            builder.setSpan(new ForegroundColorSpan(UiUtlis.getColor(R.color.Event_Green)), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            normalmessageViewHolder.tvMessageTargetContent.setText(builder);
                        }
                        if (!message.haveRead() && message.getFromUser().getUserName().equals(JMessageClient.getMyInfo().getUserName())) {
                            contentstr = "[对方未读]" + contentstr;
                            SpannableStringBuilder builder = new SpannableStringBuilder(contentstr);
                            builder.setSpan(new ForegroundColorSpan(UiUtlis.getColor(R.color.Event_Green)), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            normalmessageViewHolder.tvMessageTargetContent.setText(builder);
                        }

                    } else {
                        normalmessageViewHolder.tvMessageTargetContent.setText(contentstr);
                    }
                    //设置名称
                    UserInfo userInfo = (UserInfo) message.getTargetInfo();
                    String targetname = userInfo.getNickname();
                    normalmessageViewHolder.tvMessageTargetFullName.setText(targetname);
                    if (TextUtils.isEmpty(targetname)) {
                        normalmessageViewHolder.tvMessageTargetFullName.setText("管理员");
                        normalmessageViewHolder.tvMessageTargetTime.setText("管");
                    }
                    //设置消息未读个数
                    //获取消息数量
                    if (conversation.getUnReadMsgCnt() >= 0) {
                        if (conversation.getUnReadMsgCnt() == 0) {
                            ((MyNormalmessageViewHolder) holder).imgBageCount.setVisibility(View.GONE);
                        } else {
                            ((MyNormalmessageViewHolder) holder).imgBageCount.setVisibility(View.VISIBLE);
                            BadgeDrawable badgeDrawable = new BadgeDrawable.Builder()
                                    .type(BadgeDrawable.TYPE_NUMBER)
                                    .textSize(35)
                                    .badgeColor(UiUtlis.getColor(R.color.TopicItemNodeTextColor))
                                    .number(conversation.getUnReadMsgCnt())
                                    .textColor(UiUtlis.getColor(R.color.colorAppTheme))
                                    .cornerRadius(360)
                                    .build();
                            ((MyNormalmessageViewHolder) holder).imgBageCount.setImageDrawable(badgeDrawable);
                        }

                        if (conversation.getUnReadMsgCnt() > 99) {
                            BadgeDrawable badgeDrawable = new BadgeDrawable.Builder()
                                    .type(BadgeDrawable.TYPE_ONLY_ONE_TEXT)
                                    .textSize(35)
                                    .text1("99+")
                                    .badgeColor(UiUtlis.getColor(R.color.TopicItemNodeTextColor))
                                    .textColor(UiUtlis.getColor(R.color.colorAppTheme))
                                    .cornerRadius(360)
                                    .build();
                            ((MyNormalmessageViewHolder) holder).imgBageCount.setImageDrawable(badgeDrawable);

                        }
                    }
                    TimeFormat timeFormat = new TimeFormat(holder.itemView.getContext(), message.getCreateTime());
                    normalmessageViewHolder.tvMessageTargetTime.setText(timeFormat.getDetailTime());
                /*
                normalmessageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //清除未读角标
                        conversation.setUnReadMessageCnt(0);
                        conversation.resetUnreadCount();
                        //置顶+清除
                        setNewTop(conversation);
                        Intent intent = new Intent(normalmessageViewHolder.itemView.getContext(), ChatActivity.class);
                        //用户实体
                        UserInfo target_user = (UserInfo) conversation.getTargetInfo();
                        //如果是单聊
                        Bundle bundle = new Bundle();
                        //单聊标记false
                        bundle.putBoolean(Constants.MODE, false);
                        //单聊id
                        bundle.putString(Constants.SINGLE_ID, target_user.getUserName());
                        //单聊要用的appkey
                        bundle.putString(Constants.TARGET_APPKEY, target_user.getAppKey());
                        intent.putExtras(bundle);
                        normalmessageViewHolder.itemView.getContext().startActivity(intent);
                    }
                });
                */
                }
            }
            else
            {
                holder.itemView.setVisibility(View.GONE);
            }

        }
    }

    /**
     * 置顶新消息
     *
     * @param conversation
     */
    public void setNewTop(Conversation conversation) {
        if (conversationList.size() == 0) {
            conversationList.add(conversation);
        } else {
            //循环
            for (Conversation conversationcontent : conversationList) {
                if (conversationcontent.getId() == conversation.getId()) {
                    //移除
                    conversationList.remove(conversationcontent);
                    //添加至第一位
                    conversationList.add(0, conversation);
                    break;
                } else {
                    //直接添加
                    conversationList.add(0, conversation);
                }
            }
        }
        conversationList.remove(conversation);
        conversationList.add(0,conversation);
        //更新视图
        notifyDataSetChanged();
    }


    @Override
    public int getItemCount() {
        return conversationList == null ? 0 : conversationList.size();
    }

    /***
     * 正常类型消息的视图适配器
     */
    class MyNormalmessageViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.img_user_avator)
        CircleImageView imgUserAvator;
        @BindView(R.id.tv_message_target_full_name)
        TextView tvMessageTargetFullName;
        @BindView(R.id.tv_message_target_content)
        TextView tvMessageTargetContent;
        @BindView(R.id.tv_message_target_time)
        TextView tvMessageTargetTime;
        @BindView(R.id.img_bage_count)
        ImageView imgBageCount;

        public MyNormalmessageViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != clicktoChat) {
                        clicktoChat.tochat(getLayoutPosition(), conversationList.get(getLayoutPosition()));
                    }
                }
            });
        }
    }

    /**
     * 其他类型消息的适配器
     */
    class MyOtherMessageViewHolder extends RecyclerView.ViewHolder {

        public MyOtherMessageViewHolder(View itemView) {
            super(itemView);
        }
    }

    /**
     * 点击
     */
    public interface onClicktoChat {
        void tochat(int pos, Conversation conversation);
    }
}
